/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-15 09:50:17
 * @filename : controller/auto_renew.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    var name = 'Auto Renew', mId = 'auto_renew',
        highchartMC = require('{model}highchart'), 
        highcharts = require('highcharts'),
        tpl = require('{view}page_gold.tpl'),
        tplH = require('{view}head_gold.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');
      
    var highchartM = new highchartMC.highchartM;

    var tempOpt = {
             engine : '',
             begin_date : null,
             end_date : null,
             group : 'day'
        };

    var AutoRenewView = Backbone.View.extend({
    
        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        afterBindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            new Pikaday({
                    field: dom.find('.from_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });
             
             new Pikaday({
                    field: dom.find('.to_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });

            dom.find('.selectTime').on('change',function(){
                var val = $(this).val();
                    share.setInputDate(val,mId);
            });

            dom.find('.do').on('click',function(){
                var bool = share.getPostData(tempOpt,mId); 
                if (bool) { 
                    tthis.fetchData(tempOpt);
                }
            });
 
            dom.find('.m_head').find('input[type="text"]').on('focus',function(){
                $('#'+mId).find('.selectTime').find("option[value='']").attr("selected",true); 
            });

        },
     
        defaultOpt : function() {
             var dom = $('#'+mId);
             this.selectSite();
             share.setInputDate('last-week',mId);
             tempOpt.end_date = dom.find('.to_time').val();
             tempOpt.begin_date = dom.find('.from_time').val(); 
             tempOpt.group  = 'day';
             tempOpt.engine  = '';
        }, 
 
        selectSite : function() {
             var siteInfo =  share.getAllSites(1);
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        },  

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'total_gold',
                type : 'POST',
                data : data,
                success : function(data) {
                    //console.log(data);
                    tthis.fetchSuccess(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };
           
            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        fetchSuccess : function(data) {
            _.each(data,function(obj) {
                if (parseInt(Number(obj.AUTO_RENEWED_MEMBERS))!==0) {
                    obj.PAST_DATA = parseInt(obj.ONE_M_AGO_DATA.RE_UPGRADE_ONE_MONTH) + parseInt(obj.ONE_M_AGO_DATA.PLAN_MONTHS_ONE) + parseInt(obj.ONE_M_AGO_DATA.AUTO_RENEWED_MEMBERS); 
                    obj.AUTO_RENEWED_RATIO = (parseInt(obj.AUTO_RENEWED_MEMBERS)*100 / obj.PAST_DATA).toFixed(2);
                } else {
                    obj.AUTO_RENEWED_RATIO = 0; 
                }
            }); 

            this.details(data);
            this.changeHighChartM(data);  
        },

        details : function(data) {
            var arr = [];
                arr.push({name:'Date',val:'FMT_DATE',title:'Date'});
                arr.push({name:'Total',val:'TOTAL_GOLD',title:'Total new gold'});
                arr.push({name:'Ratio',val:'AUTO_RENEWED_RATIO',unit:'%',title:'Auto renew ratio. (=Renewed/past data)'});
                arr.push({name:'Renewed',val:'AUTO_RENEWED_MEMBERS',title:'Number of auto renewal'});
                arr.push({name:'Past Data',val:'PAST_DATA',title:'Number of members who should renew.'});
                arr.push({name:'Cancel',val:'CANCEL_AUTO_BILLING',title:'Cancelled auto billing'});
                arr.push({name:'C/R',val:'CHARGEBACK_REFUND_MEMBERS',title:'Total chargeback and refund members'});

            data = _.clone(data).reverse();
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data,arr:arr}));

        },

        changeHighChartM : function(arr) {
               
            var xAxis = highchartM.get('xAxis'),
                yAxis = highchartM.get('yAxis'),
                tooltip = highchartM.get('tooltip');
                series = highchartM.get('series'),
                chart = highchartM.get('chart'),
                title = highchartM.get('title'),
                plotOptions = highchartM.get('plotOptions');
                 
                title = {text : 'Auto Renew'}; 
                chart = {width:$('#index_right').width()}; 
                xAxis = {categories : _.pluck(arr,'DATE')}; 
                yAxis = [{
                            title: {
                                text: '',
                            },
 
                            labels: {
                                style: {
                                    color: '#5B9BD5'
                                }
                            }
                        }, { 
                            title: {
                                text: 'rate(%)',
                                style: {
                                    color: '#ff0000'
                                }
                            },
                            labels: {
                                format: '{value} %',
                                style: {
                                    color: '#ff0000'
                                }
                            },
                            opposite: true
                        }];

                tooltip = {shared: true};

                series = [

                    {
                            name: 'Auto Renew ',
                            color: '#5B9BD5',
                            type: 'line',
                            data: _.map(_.pluck(arr,'AUTO_RENEWED_MEMBERS'),function(num){return Number(num)}),  
                            tooltip: {
                                valueSuffix: ''
                            },
                            dataLabels: {
                               enabled: arr.length < share.dataLabelNum ? true : false
                            }
                    },

                     {
                            name: 'Auto Renew Ratio',
                            type: 'line',
                            color: '#ff0000',
                            yAxis: 1,
                            data: _.map(_.pluck(arr,'AUTO_RENEWED_RATIO'),function(num){return Number(num)}),
                            tooltip: {
                                valueSuffix: '%'
                            },
                            dataLabels: {
                                enabled: arr.length < share.dataLabelNum ? true : false
                            }

                        },
                    ];


                plotOptions = {};

                highchartM.set('tooltip',tooltip);
                highchartM.set('plotOptions',plotOptions); 
                highchartM.set('title',title); 
                highchartM.set('xAxis',xAxis); 
                highchartM.set('yAxis',yAxis); 
                highchartM.set('series',series);
                highchartM.set('chart',chart);
 
                //console.log(highchartM.attributes);

                this.renderHighChart();     
        }, 

        renderHighChart : function() {
             var height = share.getGraphHeight(tempOpt); 
             $('#'+mId+'_graph').height(height+'px').highcharts(highchartM.attributes);
        }


    });
	module.exports = AutoRenewView;
});




